<?php


namespace app\common\controller;

use fast\Tree;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\Db;

class Export
{
    //线索导出
    public function clue()
    {
        $where = ['create_time' => ["<", "1706716800"]];
        $count = \db('clue')->where($where)->count();

        if (empty($count)) {
            echo  "无数据";exit;
        }

        $newExcel = new Spreadsheet();
        //获取当前操作sheet的对象
        $objSheet = $newExcel->getActiveSheet();
        $date = date('Ymd', time());
        $name = '线索表';
        //设置当前sheet的标题
        $objSheet->setTitle($name);

        $objSheet->getColumnDimension('A')->setWidth(20);
        $objSheet->getColumnDimension('B')->setWidth(20);
        $objSheet->getColumnDimension('C')->setWidth(20);
        $objSheet->getColumnDimension('D')->setWidth(30);
        $objSheet->getColumnDimension('E')->setWidth(15);
        $objSheet->getColumnDimension('F')->setWidth(30);
        $objSheet->getColumnDimension('G')->setWidth(30);
        $objSheet->getColumnDimension('H')->setWidth(30);
        $objSheet->getColumnDimension('I')->setWidth(50);

        $pagesize = 3000;
        $totalpage = ceil($count / $pagesize);

        $n = 1;
        for ($i = 1; $i <= $totalpage; $i++ ) {

            $infos = \db('clue')->where($where)->page($i, $pagesize)->select();

            //设置表头
            $objSheet
                ->setCellValue('A1', '名称')
                ->setCellValue('B1', '电话')
                ->setCellValue('C1', '城市')
                ->setCellValue('D1', '线索ID')
                ->setCellValue('E1', '申请金额')
                ->setCellValue('F1', '创建时间')
                ->setCellValue('G1', '推送时间')
                ->setCellValue('H1', '更新时间')
                ->setCellValue('I1', '线索信息');

            foreach ($infos as $k => $v) {
                // 线索信息
                if (empty($v['remark'])) {
                    $infos[$k]['remark_data'] = "";
                } else {
                    $remark = json_decode($v['remark'], true);
                    if (is_array($remark)) {
                        $remarkArr = [];
                        $keys = array_keys($remark);
                        $b = false;//默认索引
                        //判断关联数组还是索引数组
                        foreach ($keys as $value) {
                            if (!is_int($value)) {
                                $b = true;
                                break;
                            }
                        }
                        //是关联数组
                        if ($b) {
                            foreach ($remark as $kk => $vv) {
                                if ($kk == '城市') {
                                } else {
                                    $remarkArr[] = $kk . '：' . $vv;
                                }
                            }
                        } else {
                            foreach ($remark as $vv) {
                                if ($v['type'] == 1) {
                                    if ($vv['name'] == '城市') {
                                    } else {
                                        $remarkArr[] = $vv['name'] . '：' . $vv['value'];
                                    }
                                } else {
                                    if (isset($vv['name']) && isset($vv['value'])) {
                                        $remarkArr[] = $vv['name'] . '：' . $vv['value'];
                                    } else {
                                        $remarkArr[] = json_encode($vv, JSON_UNESCAPED_UNICODE);
                                    }
                                }
                            }
                        }
                    } else {
                        $remarkArr = [];
                        $remarkArr[] = $v['remark'];

                    }
                    $infos[$k]['remark_data'] = implode("\r\n", $remarkArr);
                }


                $ids = explode('-', $v['city']);
                $cityNum = count($ids);
                if ($cityNum == 1) {
                    $infos[$k]['city'] = $this->getCityName($ids[0]);
                    $infos[$k]['city_remark'] = Db::name('city')->where('id', $ids[0])->value('remark');
                } elseif ($cityNum == 2) {
                    $prov = $this->getCityName($ids[0]);
                    $city = $this->getCityName($ids[1]);
                    if ($prov == $city) {
                        $infos[$k]['city'] = $prov;
                    } else {
                        $infos[$k]['city'] = $prov . '-' . $city;

                    }
                    $infos[$k]['city_remark'] = Db::name('city')->where('id', $ids[1])->value('remark');
                }

                $infos[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
                $infos[$k]['update_time'] = date('Y-m-d H:i:s', $v['update_time']);
                $infos[$k]['push_time'] = date('Y-m-d H:i:s', $v['push_time']);

                $n = $n +1;
                $objSheet->setCellValue('A' . $k, $infos[$k]['clue_name'])
                    ->setCellValue('B' . $k, $infos[$k]['phone'])
                    ->setCellValue('C' . $k, $infos[$k]['city'])
                    ->setCellValue('D' . $k, $infos[$k]['clue_id'])
                    ->setCellValue('E' . $k, $infos[$k]['apply_limit'])
                    ->setCellValue('F' . $k, $infos[$k]['create_time'])
                    ->setCellValue('G' . $k, $infos[$k]['update_time'])
                    ->setCellValue('H' . $k, $infos[$k]['push_time'])
                    ->setCellValue('I' . $k, $infos[$k]['remark_data']);
            }

            $filename = date('Y-m-d') . '线索池导出';
            //header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            //header('Content-Disposition: attachment;filename=' . $filename. $i . '.xlsx');
            //header('Cache-Control: max-age=0');

            // 保存Excel文件
            $writer = new Xlsx($newExcel);
            $writer->save(ROOT_PATH. "excel/". $filename. $i. '.xlsx');

            //$write = IOFactory::createWriter($newExcel, 'Xlsx');
            //$write->save('php://output');
        }
    }

    public function getClueData() {
        $where = ['create_time' => ["<", "1706716800"]];
        $count = \db('clue')->where($where)->count();

        if (empty($count)) {
            return false;
        }
        $pagesize = 5000;
        $totalpage = ceil($count / $pagesize);
        $page = 1;

        $infos = \db('clue')->where($where)->page($page, $pagesize)->select();

        foreach ($infos as $k => $v) {
            // 线索信息
            if (empty($v['remark'])) {
                $infos[$k]['remark_data'] = "";
            } else {
                $remark = json_decode($v['remark'], true);
                if (is_array($remark)) {
                    $remarkArr = [];
                    $keys = array_keys($remark);
                    $b = false;//默认索引
                    //判断关联数组还是索引数组
                    foreach ($keys as $value) {
                        if (!is_int($value)) {
                            $b = true;
                            break;
                        }
                    }
                    //是关联数组
                    if ($b) {
                        foreach ($remark as $kk => $vv) {
                            if ($kk == '城市') {
                            } else {
                                $remarkArr[] = $kk . '：' . $vv;
                            }
                        }
                    } else {
                        foreach ($remark as $vv) {
                            if ($v['type'] == 1) {
                                if ($vv['name'] == '城市') {
                                } else {
                                    $remarkArr[] = $vv['name'] . '：' . $vv['value'];
                                }
                            } else {
                                if (isset($vv['name']) && isset($vv['value'])) {
                                    $remarkArr[] = $vv['name'] . '：' . $vv['value'];
                                } else {
                                    $remarkArr[] = json_encode($vv, JSON_UNESCAPED_UNICODE);
                                }
                            }
                        }
                    }
                } else {
                    $remarkArr = [];
                    $remarkArr[] = $v['remark'];

                }
                $infos[$k]['remark_data'] = implode("\r\n", $remarkArr);
            }


            $ids = explode('-', $v['city']);
            $cityNum = count($ids);
            if ($cityNum == 1) {
                $infos[$k]['city'] = $this->getCityName($ids[0]);
                $infos[$k]['city_remark'] = Db::name('city')->where('id', $ids[0])->value('remark');
            } elseif ($cityNum == 2) {
                $prov = $this->getCityName($ids[0]);
                $city = $this->getCityName($ids[1]);
                if ($prov == $city) {
                    $infos[$k]['city'] = $prov;
                } else {
                    $infos[$k]['city'] = $prov . '-' . $city;

                }
                $infos[$k]['city_remark'] = Db::name('city')->where('id', $ids[1])->value('remark');
            }

            $infos[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            $infos[$k]['update_time'] = date('Y-m-d H:i:s', $v['update_time']);
            $infos[$k]['push_time'] = date('Y-m-d H:i:s', $v['push_time']);
        }
        return $infos;
    }
    public function getCityName($id)
    {
        $city = Db::name('city')->where(['id'=>$id])->find();
        return $city['name'];
    }

}